package com.tianyang.yukuaifuzs.business.main.presenter;

import com.alibaba.fastjson.JSONObject;
import com.tianyang.yukuaifuzs.business.main.bean.UserCenterOutput;
import com.tianyang.yukuaifuzs.business.main.contract.InviteCodeContract;
import com.tianyang.yukuaifuzs.business.main.model.MainModel;
import com.tianyang.yukuaifuzs.common.cache.CacheManage;
import com.tianyang.yukuaifuzs.common.cache.CacheModel;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：邀请
 * Created by xyj on 2024/3/7
 */
public class InviteCodePresenter implements InviteCodeContract.Presenter {

    private InviteCodeContract.View mView;

    private CompositeSubscription mSubscription;

    private String inviteCode;

    public InviteCodePresenter(InviteCodeContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
        UserCenterOutput output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (output != null) {
            inviteCode = output.getInvitecode();
        }
    }

    @Override
    public void compositePoster(int type) {
        mView.showLoadingDialog(false);
        Subscription subscription = MainModel.getInstance().compositePoster(inviteCode, type)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(JSONObject output) {
                        if (output != null && output.containsKey("data")) {
                            mView.showCompositePoster(output.getString("data"));
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
